package in.muton.edushare.components.forms.usersettings;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.error.ErrorPanel;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.vo.Users;

public class PsswdForm extends Panel {

	public PsswdForm(String id, IModel<Users> aModel) {
		super(id);
		this.model = aModel;
		Form<Void> f = new Form<Void>("passwordChangeForm") {
			@Override
			public void onSubmit() {
				if (model.getObject().getPassword().compareTo(
						DigestUtils.sha256Hex(origPwd)) != 0) {
					error = "The original password you provided is incorrect";
				} else if (newPwd1.compareTo(newPwd2) != 0) {
					error = "The new Password and repeat new Password fields do not match";
				} else if (newPwd1.length() < ApplicationConstants.MIN_PASSWORD_LENGTH) {
					error = "The password must be at least "
							+ ApplicationConstants.MIN_PASSWORD_LENGTH
							+ "long.";
				} else {
					model.getObject().setPassword(newPwd1);
					error = "Password changed successfully";
					EduShareSession.get().getSessionORMInterface()
							.commitAllChanges();
				}
			}

			private static final long serialVersionUID = 673709739129720147L;
		};
		add(f);
		f.setDefaultModel(new CompoundPropertyModel<PsswdForm>(this));
		f.add(new PasswordTextField("origPwd"));
		f.add(new PasswordTextField("newPwd1"));
		f.add(new PasswordTextField("newPwd2"));
		f.add(new ErrorPanel("errorFdb", new PropertyModel<String>(this,
				"error")));
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getError() {
		return error;
	}

	public String getOrigPwd() {
		return origPwd;
	}

	public void setOrigPwd(String origPwd) {
		this.origPwd = origPwd;
	}

	public String getNewPwd1() {
		return newPwd1;
	}

	public void setNewPwd1(String newPwd1) {
		this.newPwd1 = newPwd1;
	}

	public String getNewPwd2() {
		return newPwd2;
	}

	public void setNewPwd2(String newPwd2) {
		this.newPwd2 = newPwd2;
	}

	private IModel<Users> model;
	private String error = "";
	private String origPwd = "";
	private String newPwd1 = "";
	private String newPwd2 = "";

	private static final long serialVersionUID = 2387817477034623264L;
}
